import torch


if __name__ == '__main__':
    # 输入和目标
    x = torch.tensor([1.0], requires_grad=False)
    target = torch.tensor([3.0])

    # 初始化参数（需要梯度）
    w1 = torch.tensor([2.0], requires_grad=True)
    b1 = torch.tensor([1.0], requires_grad=True)
    w2 = torch.tensor([1.0], requires_grad=True)
    b2 = torch.tensor([0.5], requires_grad=True)

    # 前向传播
    h = w1 * x + b1
    y = w2 * h + b2
    loss = (y - target) ** 2

    # 反向传播
    loss.backward()

    # 打印梯度
    print("Gradient of w1:", w1.grad)  # 输出: tensor([1.])
    print("Gradient of b1:", b1.grad)  # 输出: tensor([1.])
    print("Gradient of w2:", w2.grad)  # 输出: tensor([3.])
    print("Gradient of b2:", b2.grad)  # 输出: tensor([1.])
